package com.ybbase.framework.controller.flow.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ybbase.framework.base.controller.BaseController;
import com.ybbase.framework.base.model.ResponseBean;
import com.ybbase.framework.common.constant.CommonResultCode;
import com.ybbase.framework.common.util.BeanUtil;
import com.ybbase.framework.model.po.flow.*;
import com.ybbase.framework.model.po.system.Organization;
import com.ybbase.framework.model.po.system.User;
import com.ybbase.framework.model.vo.flow.NodeUsergroupVO;
import com.ybbase.framework.service.flow.ActionConfigService;
import com.ybbase.framework.service.flow.FlowConfigService;
import com.ybbase.framework.service.flow.InstanceRecordService;
import com.ybbase.framework.service.flow.NodeConfigService;
import com.ybbase.framework.service.system.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 流程节点配置 Controller
 * @author cg
 * @date 2019-11-04 19:14
 * @since 4.0
 */
@RestController
@RequestMapping("/nodeConfig")
public class FlowNodeConfigController extends BaseController {

    private static final Logger logger = LogManager.getLogger(FlowNodeConfigController.class);

    @Autowired
    NodeConfigService nodeConfigService;
    @Autowired
    ActionConfigService actionConfigService;
    @Autowired
    UserService userService;
    @Autowired
    InstanceRecordService instanceRecordService;
    @Autowired
    FlowConfigService flowConfigService;


    /**
     * 根据节点编码获取节点配置列表
     * @param nodeConfig 节点配置
     * @return ResponseBean
     * @author cg
     * @date 2019-11-04 20:20
     * @since 4.0
     */
    @GetMapping("/getNodeConfigList")
    @ApiOperation(value = "根据节点编码获取节点配置列表", notes = "根据节点编码获取节点配置列表")
    @ApiImplicitParam(name = "nodeId", value = "节点编码", dataType = "String")
    public ResponseBean getNodeConfigList(NodeConfig nodeConfig,@RequestParam(name = "current", defaultValue = "1") int pageIndex,
                                          @RequestParam(name = "size", defaultValue = "20") int step){
        QueryWrapper<NodeConfig> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(nodeConfig.getNodeCode())){
            wrapper.lambda().eq(NodeConfig::getNodeCode, nodeConfig.getNodeCode());
        }
        Page<NodeConfig> page = new Page(pageIndex,step);
        nodeConfigService.page(page,wrapper);
        try{
            if (!page.getRecords().isEmpty()){
                for(NodeConfig n:page.getRecords()){
                    List<NodeUsergroup> list = nodeConfigService.getUserByFlowNode(n.getFlowCode(),n.getNodeCode());
                    if(list!=null&&!list.isEmpty()){
                        String userNames = "";
                        for(NodeUsergroup nodeUsergroup:list){
                            if(StringUtils.isNotEmpty(nodeUsergroup.getUserIds())){
                                String[] ids =nodeUsergroup.getUserIds().split(",");
                                for(String id:ids){
                                    if (StringUtils.isNotEmpty(id)){
                                        userNames = userNames + userService.getById(Integer.parseInt(id)).getName() +"|";
                                    }
                                }
                            }

                        }
                        n.setUserNames(userNames);
                    }
        //            List<ActionConfig> actionConfigs = actionConfigService.getActionListByCode(n.getFlowCode(), n.getNodeCode());
        //            if(actionConfigs!=null&&!actionConfigs.isEmpty()){
        //                String as = "";
        //                for(ActionConfig a:actionConfigs){
        //                    as = StringUtils.isNotEmpty(as)?as +"-"+a.getActionCode():a.getActionCode();
        //                }
        //                n.setActionCodes(as.split("-"));
        //            }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("根据节点编码获取节点配置列表异常", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据节点编码获取节点配置列表异常");
        }
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(), CommonResultCode.SUCCESS.getMsg(), page);
    }

    /**
     * 根据节点编码获取节点数据
     * @param nodeId 节点编码
     * @return ResponseBean
     * @author cg
     * @date 2019-11-11 15:30
     * @since 4.0
     */
    @GetMapping("/getNodeConfig")
    @ApiOperation(value = "根据节点编码获取节点数据", notes = "根据节点编码获取节点数据")
    @ApiImplicitParam(name = "nodeId", value = "节点编码", dataType = "String")
    public ResponseBean getNodeConfig(@RequestParam String nodeId){
        NodeConfig config = new NodeConfig();
        try {
            config = nodeConfigService.getById(Long.parseLong(nodeId));
            //List<NodeUsergroup> nodeUsergroups = nodeConfigService.getUserByFlowNode(config.getFlowCode(),config.getNodeCode());
            //if(nodeUsergroups!=null&&!nodeUsergroups.isEmpty()){
            //    List<User> list = nodeConfigService.getUserByNodeConfig(nodeUsergroups.get(0).getUserIds());
            //    if(list!=null&&list.size()>0){
            //        String userIds = "";
            //        String userNames = "";
            //        for (User u:list){
            //            userIds = userIds + "," + u.getId();
            //            userNames = userNames + "|" + u.getDefaultOrgName() +"-"+u.getName();
            //        }
            //        config.setChoosePeople(userIds);
            //        config.setChoosePeopleNames(userNames);
            //    }
            //}
            //config.setNodeNameCg(config.getNodeName());
            List<NodeUsergroup> list = nodeConfigService.getUserByFlowNode(config.getFlowCode(), String.valueOf(config.getNodeCode()));
            if(list!=null&&!list.isEmpty()){
                List<NodeUsergroupVO> uglist = new ArrayList<>();
                for(NodeUsergroup n:list){
                    NodeUsergroupVO ngv = new NodeUsergroupVO();
                    ngv.setNodeUsergroupId(n.getId());
                    User user = userService.getById(n.getUserIds());
                    ngv.setOperatorName(user!=null?user.getName():"");
                    ngv.setOrganId(n.getOrgIds());
                    ngv.setOrganName(n.getOrgFlowType());
                    uglist.add(ngv);
                }
                config.setUsergroupList(uglist);
            }
            QueryWrapper<FlowConfig> flowConfigQueryWrapper = new QueryWrapper<>();
            flowConfigQueryWrapper.lambda().eq(FlowConfig::getFlowCode, config.getFlowCode());
            FlowConfig flowConfig = flowConfigService.getOne(flowConfigQueryWrapper);
            config.setFlowNames(flowConfig!=null?flowConfig.getFlowName():"");
            //List<ActionConfig> actionConfigs = actionConfigService.getActionListByCode(config.getFlowCode(), config.getNodeCode());
            //if(actionConfigs!=null&&!actionConfigs.isEmpty()){
            //    String as = "";
            //    for(ActionConfig a:actionConfigs){
            //        as = StringUtils.isNotEmpty(as)?as +"-"+a.getActionCode():a.getActionCode();
            //    }
            //    config.setActionCodes(as.split("-"));
            //}
        }catch (Exception e){
            e.printStackTrace();
            logger.error("根据节点编码获取节点数据", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据节点编码获取节点配置列表异常");
        }
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(),CommonResultCode.SUCCESS.getMsg(), config);
    }


    /**
     * 保存节点配置实体
     * @param nodeConfig 节点配置
     * @return ResponseBean
     * @author cg
     * @date 2019-11-04 20:23
     * @since 4.0
     */
    @PostMapping("/saveNodeConfig")
    @ApiOperation(value = "保存节点配置实体", notes = "保存节点配置实体")
    @ApiImplicitParam(name = "gatewayConfig", value = "节点配置", dataType = "网关配置")
    public ResponseBean saveNodeConfig(HttpServletRequest request){
        try{
            BeanUtil beanUtil = new BeanUtil();
            NodeConfig nodeConfig = (NodeConfig) beanUtil.mapToObject(request.getParameterMap(), NodeConfig.class);
            nodeConfig.setOrderCode(nodeConfig.getNodeCode()+"Audit");
            nodeConfig.setVersion("1");
            nodeConfig.setNodeName(nodeConfig.getNodeNameCg());
            nodeConfigService.saveNodeConfig(nodeConfig);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("保存节点配置实体异常", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据节点编码获取节点配置列表异常");
        }
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(),"保存节点"+CommonResultCode.SUCCESS.getMsg());
    }

    /**
     * 编辑节点配置实体
     * @param nodeConfig 节点配置
     * @return ResponseBean
     * @author cg
     * @date 2019-11-04 20:25
     * @since 4.0
     */
    @PostMapping("/editNodeConfig")
    @ApiOperation(value = "编辑节点配置实体", notes = "编辑节点配置实体")
    @ApiImplicitParam(name = "gatewayConfig", value = "节点配置", dataType = "网关配置")
    public ResponseBean editNodeConfig(HttpServletRequest request){
        try{
            BeanUtil beanUtil = new BeanUtil();
            NodeConfig nodeConfig = (NodeConfig) beanUtil.mapToObject(request.getParameterMap(), NodeConfig.class);
            nodeConfig.setNodeName(nodeConfig.getNodeNameCg());
            nodeConfigService.editNodeConfig(nodeConfig);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("编辑节点配置实体异常", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "编辑节点配置实体异常");
        }
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(),"编辑节点"+CommonResultCode.SUCCESS.getMsg());
    }

    /**
     * 删除节点配置
     * @param nodeId 节点编码
     * @return ResponseBean
     * @author cg
     * @date 2019-11-04 20:34
     * @since 4.0
     */
    @DeleteMapping("/delNodeConfig")
    @ApiOperation(value = "删除节点配置", notes = "删除节点配置")
    @ApiImplicitParam(name = "nodeId", value = "节点Id", dataType = "String")
    public ResponseBean delNodeConfig(String nodeId){
        try{
            ////判断当前流程是否有正在运行的流程
            //NodeConfig config = nodeConfigService.getById(Long.parseLong(nodeId));
            //QueryWrapper<InstanceRecord> queryWrapper = new QueryWrapper<>();
            //queryWrapper.lambda().eq(InstanceRecord::getRunDefinitionId, config.getFlowCode());
            //queryWrapper.lambda().eq(InstanceRecord::getIsFinish, 0);
            //List<InstanceRecord> instanceRecords =instanceRecordService.list(queryWrapper);
            //if(instanceRecords!=null&&!instanceRecords.isEmpty()){
            //    return new ResponseBean(CommonResultCode.FAIL.getCode(), "该节点所在流程正在运行，不能删除该节点");
            //}
            ////判断流程节点是否已经指定审核人
            //List<NodeUsergroup> list = nodeConfigService.getUserByFlowNode(config.getFlowCode(), config.getNodeCode());
            //if (list!=null&&!list.isEmpty()){
            //    return new ResponseBean(CommonResultCode.FAIL.getCode(), "该节点已经配置审核用户，请清空审核用户后，再次删除");
            //}
            nodeConfigService.removeByNodeId(Integer.parseInt(nodeId));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("删除节点配置错误", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "删除节点配置错误");
        }
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(),CommonResultCode.SUCCESS.getMsg());
    }

    /**
     * 根据流程编码获取流程节点配置
     * @param flowCode 流程编码
     * @return
     * @author cg
     * @date 2019-11-04 20:37
     * @since 4.0
     */
    @GetMapping("/getNodeConfigByFlowCode")
    @ApiOperation(value = "根据流程编码获取流程节点配置", notes = "根据流程编码获取流程节点配置")
    @ApiImplicitParam(name = "flowCode", value = "流程编码", dataType = "String")
    public ResponseBean getNodeConfigByFlowCode(String flowCode){
        List<NodeConfig> list = new ArrayList<>();
        try {
            QueryWrapper<NodeConfig> nodeConfigQueryWrapper = new QueryWrapper<>();
            nodeConfigQueryWrapper.lambda().eq(NodeConfig::getFlowCode, flowCode);
            list = nodeConfigService.list(nodeConfigQueryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("根据流程编码获取流程节点配置错误", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据流程编码获取流程节点配置错误");
        }
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(),CommonResultCode.SUCCESS.getMsg(),list);
    }

    /**
     * 根据流程编码获取流程节点用户配置
     * @param flowCode 流程编码
     * @param nodeId 节点编码
     * @return ResponseBean
     * @author cg
     * @date 2019-11-04 20:44
     * @since 4.0
     */
    @GetMapping("/getUserByFlowNode")
    @ApiOperation(value = "根据流程编码获取流程节点用户配置", notes = "根据流程编码获取流程节点配置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "flowCode", value = "流程编码", dataType = "String"),
            @ApiImplicitParam(name = "nodeId", value = "节点编码", dataType = "String")
    })
    public ResponseBean getUserByFlowNode(String flowCode,String nodeId){
        List<NodeUsergroup> list = new ArrayList<>();
        try{
            list = nodeConfigService.getUserByFlowNode(flowCode,nodeId);
            if(list!=null&&!list.isEmpty()){
                if(list!=null&&!list.isEmpty()){
                    for(NodeUsergroup nodeUsergroup:list){
                        nodeUsergroup.setUserNames(userService.getById(Integer.parseInt(nodeUsergroup.getUserIds())).getName());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("根据流程编码获取流程节点用户配置", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据流程编码获取流程节点用户配置错误");
        }
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(),CommonResultCode.SUCCESS.getMsg(),list);
    }

    /**
     * 保存usergroup
     * @param nodeId 节点编码
     * @param organId 组织机构编码
     * @param userId 用户编码
     * @return
     * @author cg
     * @date 2020-03-01 22:28
     * @since cloud2.0
    */
    @GetMapping("/saveUserGroup")
    public ResponseBean saveUserGroup(Integer nodeId,Integer organId,Integer userId){
        try {
            NodeConfig nodeConfig = nodeConfigService.getById(nodeId);
            QueryWrapper<NodeUsergroup> nw = new QueryWrapper<>();
            nw.lambda().eq(NodeUsergroup::getFlowCode,nodeConfig!=null?nodeConfig.getFlowCode():"");
            nw.lambda().eq(NodeUsergroup::getNodeCode, nodeConfig!=null?nodeConfig.getNodeCode():"");
            nw.lambda().eq(NodeUsergroup::getOrgIds,organId+"");
            nw.lambda().eq(NodeUsergroup::getUserIds, userId+"");
            List<NodeUsergroup> list = nodeConfigService.getNodeGroup(nw);
            if (list!=null&&!list.isEmpty()){
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "请勿为同一流程节点重复添加相同的审核人");
            }
            nodeConfigService.saveConfigUserGroup(nodeId,organId,userId);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "保存审核人"+CommonResultCode.FAIL.getMsg());
        }
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(),"保存审核人"+CommonResultCode.SUCCESS.getMsg());
    }

    /**
     * 删除流程编码获取流程节点用户配置
     * @param id 节点用户配置编码
     * @return ResponseBean
     * @return
     * @author cg
     * @date 2019-11-12 18:52
     * @since 4.0
     */
    @DeleteMapping("/removeUserGroup")
    @ApiOperation(value = "删除流程编码获取流程节点用户配置", notes = "删除流程编码获取流程节点用户配置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "节点用户配置编码", dataType = "String")
    })
    public ResponseBean removeUserGroup(String id){
        try {
            nodeConfigService.removeUserGroup(Integer.parseInt(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("删除流程编码获取流程节点用户配置", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "删除节点配置错误");
        }
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(),CommonResultCode.SUCCESS.getMsg());
    }



}
